import json
from Manager.views.service import my_page
from django.http import JsonResponse, HttpResponse, HttpResponseRedirect
from django.shortcuts import render, redirect
from django.views import View
from Manager.models import *
from Rbac.models import *
from Django_Admin.enumType import ApiType_choices
from Rbac.utils.login_deco import *


# 分账户列表
@auth
def CChannelist(request):
    off = request.GET.get('offset', None)
    lim = request.GET.get('limit', None)
    search = request.GET.get('search', None)
    if search is None:
        # 从customer、channel两张表，分别查出用户代码、交易通道和行情通道
        customerid = Customer.objects.all()
        tdchannelid = Channel.objects.all().exclude(terminaltype="2").values("channelid", "apitype")
        mdchannelid = Channel.objects.all().exclude(terminaltype="1")
        return render(
            request,
            "cchannel.html", {
                'customerid': customerid,
                'tdchannelid': tdchannelid,
                'mdchannelid': mdchannelid,
            }
        )
    else:
        if search:
            CClist = Customerchannelrel.objects.values().filter(accountid__contains=search)
        else:
            CClist = Customerchannelrel.objects.values()
    CClist = list(CClist)
    for ccinfo in CClist:
        ccinfo['option'] = ccinfo['id']
        ccinfo['tdapitype'] = ApiType_choices.get(ccinfo['tdapitype'])
    result = my_page(CClist, lim, off)
    return JsonResponse(result, safe=False)


# 分账户增删改查
def cchannel_modify(request):
    ##拿到登录用户id
    userid = request.session["id"]
    isdelete = Customer.objects.filter(customerid=userid).filter(
        roles__permissions__url__endswith='customer_channelist(delete)')
    ismodify = Customer.objects.filter(customerid=userid).filter(
        roles__permissions__url__endswith='customer_channelist(modify)')
    isadd = Customer.objects.filter(customerid=userid).filter(
        roles__permissions__url__endswith='customer_channelist(add)')
    if request.method == "GET":
        id = request.GET["id"]
        item = Customerchannelrel.objects.filter(id=id).values().first()
        if item:
            row = {
                'customerid': item['customerid_id'],
                'tdchannelid': item['tdchannelid_id'],
                'mdchannelid': item['mdchannelid_id'],
                'accountid': item['accountid'],
                'tdapitype': item['tdapitype'],
                'assetno': item['assetno'],
                'combino': item['combino'],
                'apiaccountid': item['apiaccountid'],
                'apiinvestorid': item['apiinvestorid'],
            }
            return JsonResponse(row, safe=False)
    else:
        if request.POST.get('delete', None):
            if isdelete:
                CChannelID = request.POST.get('id')
                Customerchannelrel.objects.filter(id=CChannelID).delete()
                return JsonResponse('y', safe=False)
            else:
                return JsonResponse("该用户无操作权限！", safe=False)
        else:
            data = request.POST
            for i in data:
                data = json.loads(i)
            try:
                customerobj = Customer.objects.get(customerid=data['customerid'])
                if data['tdchannelid']:
                    tdchannelobj = Channel.objects.get(channelid=data['tdchannelid'])
                    if data['mdchannelid']:
                        mdchannelobj = Channel.objects.get(channelid=data['mdchannelid'])
                        t = "bt"
                    else:
                        t = "td"
                else:
                    mdchannelobj = Channel.objects.get(channelid=data['mdchannelid'])
                    if data['tdchannelid']:
                        tdchannelobj = Channel.objects.get(channelid=data['tdchannelid'])
                        t = "bt"
                    else:
                        t = "md"

                if data["id"] and Customerchannelrel.objects.filter(id=data['id']).count() >= 1:
                    if ismodify:
                        if t == 'bt':
                            Customerchannelrel.objects.filter(id=data['id']).update(
                                customerid=customerobj,
                                tdchannelid=tdchannelobj,
                                mdchannelid=mdchannelobj,
                                accountid=data['accountid'],
                                tdapitype=data['tdapitype'],
                                assetno=data['assetno'],
                                combino=data['combino'],
                                apiaccountid=data['apiaccountid'],
                                apiinvestorid=data['apiinvestorid'],
                            )
                        elif t == "td":
                            Customerchannelrel.objects.filter(id=data['id']).update(
                                customerid=customerobj,
                                tdchannelid=tdchannelobj,
                                accountid=data['accountid'],
                                tdapitype=data['tdapitype'],
                                assetno=data['assetno'],
                                combino=data['combino'],
                                apiaccountid=data['apiaccountid'],
                                apiinvestorid=data['apiinvestorid'],
                            )
                        else:
                            Customerchannelrel.objects.filter(id=data['id']).update(
                                customerid=customerobj,
                                mdchannelid=mdchannelobj,
                                accountid=data['accountid'],
                                tdapitype=data['tdapitype'],
                                assetno=data['assetno'],
                                combino=data['combino'],
                                apiaccountid=data['apiaccountid'],
                                apiinvestorid=data['apiinvestorid'],
                            )
                        return HttpResponse('y')
                    else:
                        return HttpResponse("该用户无操作权限")
                else:
                    if isadd:
                        if Customerchannelrel.objects.filter(accountid=data['accountid']).count() >= 1:
                            return HttpResponse("分账号代码已存在！")
                        if t == 'bt':
                            Customerchannelrel.objects.create(
                                customerid=customerobj,
                                tdchannelid=tdchannelobj,
                                mdchannelid=mdchannelobj,
                                accountid=data['accountid'],
                                tdapitype=data['tdapitype'],
                                assetno=data['assetno'],
                                combino=data['combino'],
                                apiaccountid=data['apiaccountid'],
                                apiinvestorid=data['apiinvestorid'],
                            )
                        elif t == "td":
                            Customerchannelrel.objects.create(
                                customerid=customerobj,
                                tdchannelid=tdchannelobj,
                                accountid=data['accountid'],
                                tdapitype=data['tdapitype'],
                                assetno=data['assetno'],
                                combino=data['combino'],
                                apiaccountid=data['apiaccountid'],
                                apiinvestorid=data['apiinvestorid'],
                            )
                        else:
                            Customerchannelrel.objects.create(
                                customerid=customerobj,
                                mdchannelid=mdchannelobj,
                                accountid=data['accountid'],
                                tdapitype=data['tdapitype'],
                                assetno=data['assetno'],
                                combino=data['combino'],
                                apiaccountid=data['apiaccountid'],
                                apiinvestorid=data['apiinvestorid'],
                            )
                        return HttpResponse("y")
                    else:
                        return HttpResponse("该用户无操作权限")
            except Exception as e:
                return HttpResponse(e)
    return render(request, 'cchannel.html')


# 根据分账户的tdchannelid，到实体账户里面查询userid也就是交易账号
def cchannel_userid(request):
    channelid = request.POST.get("channelid")
    userset = Channel.objects.filter(channelid=channelid).values("userid")
    userlist = list(userset)
    userid = userlist[0].get("userid")

    return HttpResponse(userid)
